<?php
/**
 * 订单服务层
 */
namespace app\service;
use app\api\controller\v1\Mail;
use app\api\logic\SendMuLogic;
use think\Db;
use app\service\UserWeixinService;
use app\service\TechnWeixinService;
use app\service\TechnService;
use think\log;
class OrderService
{
	/**
	 * 订单状态
	 */
	public static $status_array = [
		0 => ['value' => 0, 'name' => '待支付'],
		1 => ['value' => 1, 'name' => '待接单'],
		2 => ['value' => 2, 'name' => '已接单'],
		3 => ['value' => 3, 'name' => '已出发'],
		4 => ['value' => 4, 'name' => '已到达'],
		5 => ['value' => 5, 'name' => '开始服务'],
		6 => ['value' => 6, 'name' => '已完成'],
		7 => ['value' => 7, 'name' => '取消支付'],
		8 => ['value' => 8, 'name' => '已关闭'],
		9 => ['value' => 9, 'name' => '客户待补单'],
		10 => ['value' => 10, 'name' => '完成补单'],
		11 => ['value' => 11, 'name' => '申诉补单'],
		12 => ['value' => 12, 'name' => '用户退款'],
		13 => ['value' => 13, 'name' => '联系异常'],
		14 => ['value' => 14, 'name' => '技师拒单'],
		15 => ['value' => 15, 'name' => '支付超时'],
		16 => ['value' => 16, 'name' => '补单完成'],
		17 => ['value' => 17, 'name' => '技师不接单'],
	];

	/**
	 * 订单支付处理
	 */
	public static function OrderPayHandle($params = [])
	{
		//订单信息
		if(empty($params['order']))
		{
			return ['code' => -1, 'msg' => '资源不存在或已被删除'];
		}
		if($params['order']['status'] > 0 && $params['order']['status']!=8)
		{
			return ['code' => 0, 'msg' => '状态不可操作'];
		}
		// 支付方式
		if(empty($params['payment']))
		{
			return ['code' => -1, 'msg' => '支付方式有误'];
		}
		// 支付参数
		$pay_price = isset($params['pay']['pay_price']) ? $params['pay']['pay_price'] : 0;
		// 开启事务
		Db::startTrans();
		//写入支付日志
		$pay_log_id = Db::name('pay_log')->insertGetId([
			'order_id'      => $params['order']['id'],
			'trade_no'      => isset($params['pay']['trade_no']) ? $params['pay']['trade_no'] : '',
			'buyer_user'    => isset($params['pay']['buyer_user']) ? $params['pay']['buyer_user'] : '',
			'pay_price'     => $pay_price,
			'total_price'   => $params['order']['total_price'],
			'subject'       => isset($params['pay']['subject']) ? $params['pay']['subject'] : '订单支付',
			'payment'       => $params['payment']['payment'],
			'payment_name'  => $params['payment']['name'],
			'business_type' => 1,
			'add_time' => time()
		]);
		if($pay_log_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '支付日志添加失败'];
		}
		//订单更新数据
		$upd_data = [
			'status' => 1,
			'pay_status' => 1,
			'pay_price' => $pay_price,
			'pay_time' => time(),
			'upd_time' => time()
		];
		//更新订单状态
		if(!Db::name('order')->where(['id' => $params['order']['id']])->update($upd_data))
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单更新失败'];
		}
		//添加状态日志
		$status_array = self::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $params['order']['id'],
			'original_status' => $params['order']['status'],
			'new_status' => $upd_data['status'],
			'msg' => '支付['.$status_array[$params['order']['status']]['name'].'-'.$status_array[$upd_data['status']]['name'].']',
			'identity_type' => 'system',
			'identity_id' => 0,
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单历史状态添加失败'];
		}
		//写入结算数据
		$balance_data = [];
		//结算剩余百分比
		$balance_surplus_scale = 100;
		//服务剩余费用
		$balance_surplus_price = $params['order']['price']-$params['order']['preferential_price'];
		//查询技师等级写入结算数据

		//渠道费
		$preferential_price=0;

        //查询技师信息
        $techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
        $orders_num = $techn_info['orders_num']+1;
        if($params['order']['preferential_price'] > 0){
            $quan = json_decode($params['order']['extension_data'],true);
            log::write($quan);
            $quan_status = Db::name('coupon')->where('id',$quan[0]['ext']['coupon_id'])->value('bear_one');
        }




        //上级返利  技师上级分成

        $userupid=db::name('user_bd')->where('bduid',$techn_info['user_id'])->value('user_id');

        if(!empty($userupid) && $params['order']['budan_id'] == 0){

            //上级用户
            $user=db::name('user')->where('id',$userupid)->find();

            $techn_up=Db::name('techn')->where('user_id',$userupid)->find();

            $user_bd=db::name('user_bd')->where(['user_id'=>$userupid,'bduid'=>$techn_info['user_id']])->find();


            if(!empty($techn_up)){//技师推技师
                $bl=$user_bd['bd_bl2'];
            }else{//技师推用户
                $bl=$user_bd['bd_bl'];
            }

            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0&&$no_money>0){
                $balance_data[] = [
                    'balance_type' => 4,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $userupid,
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '技师分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];

                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;

            }
        }

        $user_bl = 0;
        //用户分佣  用户分享分佣
        if($params['order']['poster_id']>0 && $params['order']['poster_id']!=$params['order']['user_id'] && $params['order']['budan_id'] == 0){
            $user=db::name('user')->where('id',$params['order']['poster_id'])->find();
            //此处判断渠道类型  如果有业务员上级 分两部分佣金
            if ($user['g_uid']>0){
                $guid = Db::name('user')->where('id',$user['g_uid'])->find();
                $bl=$guid['share_bl'];
                $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
                if($bl>0){
                    $balance_data[] = [
                        'balance_type' => 7,
                        'order_id' => $params['order']['id'],
                        'identity_type' => 'user',
                        'identity_id' => $guid['id'],
                        'divide_into' => $bl,
                        'price' => $params['order']['price']-$params['order']['preferential_price'],
                        'no_money' => $no_money,
                        'msg' => '业务员分拥',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype'=>3
                    ];
                    $preferential_price+=$no_money;
                    $balance_surplus_price -= $no_money;
                }

            }

            $daytime=strtotime(date('Y-m-d'));
            $add_time=$user['add_time'];
            $bl=$user['share_bl'];
            $user_bl=$bl;
            $no_money=round(($params['order']['price']-$params['order']['preferential_price'])*$bl/100,2);
            if($bl>0){
                $balance_data[] = [
                    'balance_type' => 3,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'user',
                    'identity_id' => $params['order']['poster_id'],
                    'divide_into' => $bl,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $no_money,
                    'msg' => '用户分佣',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>1
                ];
                $preferential_price+=$no_money;
                $balance_surplus_price -= $no_money;
            }
        }

        if($params['order']['price']>0){
            //查询技师实时数据
            $techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();

            if(!empty($techn_last_info))
            {
                //技师分成比例
                $techn_divide_into = empty($techn_last_info['divide_into']) ? 60 : $techn_last_info['divide_into'];
                //技师分成金额
                if (isset($quan_status) && $quan_status != 1){
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($balance_surplus_price));
                }else{
                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($balance_surplus_price+$params['order']['preferential_price']));
                }
//                if ($user_bl > 1){
//                    $techn_no_money = PriceNumberFormat(($techn_divide_into/100)*($params['order']['price']-$preferential_price-$params['order']['preferential_price']));
//                }
                //技师服务费用结算数据
                $techn_service_data = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'techn',
                    'identity_id' => $params['order']['techn_id'],
                    'divide_into' => $techn_divide_into,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
                    'msg' => '技师分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
                $balance_surplus_scale -= $techn_service_data['divide_into'];
                $balance_surplus_price -= $techn_service_data['no_money'];
                $balance_data[] = $techn_service_data;
            }
        }






        if($params['order']['price']>0){

            //查看机构结算数据
            $proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
            if(!empty($proxy_info))
            {
                if($balance_surplus_price >= 0.01)
                {
                    //机构分成比例
                    $proxy_commission = $proxy_info['commission'];
                    //机构分成金额
                    $proxy_no_money = PriceNumberFormat(($proxy_commission/100)*($params['order']['price']-$params['order']['preferential_price']));
                    //机构结算数据
                    $proxy_service_data = [
                        'balance_type' => 1,
                        'order_id' => $params['order']['id'],
                        'identity_type' => 'proxy',
                        'identity_id' => $proxy_info['proxy_id'],
                        'divide_into' => $proxy_commission,
                        'price' => $params['order']['price']-$params['order']['preferential_price'],
                        'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
                        'msg' => '机构分成',
                        'add_time' => time(),
                        'upd_time' => time(),
                        'khtype'=>2
                    ];
                    $balance_surplus_scale -= $proxy_service_data['divide_into'];
                    $balance_surplus_price -= $proxy_service_data['no_money'];
                    $balance_data[] = $proxy_service_data;
                }
            }
            //系统平台结算数据
            if($balance_surplus_price >= 0.01)
            {
                $balance_data[] = [
                    'balance_type' => 1,
                    'order_id' => $params['order']['id'],
                    'identity_type' => 'system',
                    'identity_id' => 0,
                    'divide_into' => $balance_surplus_scale,
                    'price' => $params['order']['price']-$params['order']['preferential_price'],
                    'no_money' => $balance_surplus_price,
                    'msg' => '平台分成',
                    'add_time' => time(),
                    'upd_time' => time(),
                    'khtype'=>2
                ];
            }


        }
        if ($params['order']['travel_price'] > 0 ){
            //技师出行费用结算数据
            $balance_data[] = [
                'balance_type' => 2,
                'order_id' => $params['order']['id'],
                'identity_type' => 'techn',
                'identity_id' => $params['order']['techn_id'],
                'divide_into' => 100,
                'price' => $params['order']['travel_price'],
                'no_money' => $params['order']['travel_price'],
                'msg' => '技师出行',
                'add_time' => time(),
                'upd_time' => time(),
                'khtype'=>2
            ];
        }

		if(!empty($balance_data))
		{
            Db::name('techn')->where('id',$params['order']['techn_id'])->update(['orders_num'=>$orders_num]);

			$balance_count = Db::name('balance')->insertAll($balance_data);
			if($balance_count <= 0)
			{
				Db::rollback();
			    return ['code' => -1, 'msg' => '结算数据添加失败'];
			}
//            //增加技师周期内绩效
//            $have_result = Db::name('techn_last')->where('techn_id',$params['order']['techn_id'])->field('total_result')->find();
//            $now_result = $have_result['total_result']+$params['order']['price'];
//            $last_re = Db::name('techn_last')->where('techn_id',$params['order']['techn_id'])->update(['temp_result'=>$now_result]);
//            if (!$last_re){
//                Db::rollback();
//                return ['code' => -1, 'msg' => '结算数据添加失败'];
//            }
        }


		//提交事务
		Db::commit();
		if(!empty($techn_info))
		{


		        TechnService::TechnPreTimey($params['order']['techn_id']);

		  //  if($techn_info['work_status']==1){
			 //   //电话通知技师接单
			 //   ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $techn_info['mobile'], 'TTS_269350009');
		  //  }else{
		  //      if($params['order']['pre_start_time']-time()<3600){
			 //       ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $techn_info['mobile'], 'TTS_269350009');
		  //      }else{

		            //走队列
            		//创建任务： 项目命名空间\模块\文件夹\控制器@方法
            // 		$job = "app\service\QueuesService@ivrCall";
            // 		//延时时间
            // 		$delayed_second = 0;
            // 		$queues_data = ['mobile' => $techn_info['mobile']];
            // 		\think\Queue::later($delayed_second, $job, $queues_data, 'ivrCall');
		  //      }
		  //  }


		  //  if($params['order']['pre_start_time']-time()<3600){
		  //      $second=0;


//            打电话
//		        ivrCall('LTAI5tCfyuqK4o58i6MH3qH2', 'xXOnPRM4tMimqDVR4e1Ms5crn0lUtP', '057156104394', $techn_info['mobile'], 'TTS_269350009');



		  //      db::name('order')->where('id',$params['order']['id'])->setInc('tel_num',1);
		  //  }else{
		        $second=5;
		        $job = "app\service\QueuesService@ivrCall";
         		//延时时间
         		$delayed_second = 300;
         		$queues_data = ['id' => $params['order']['id'],'mobile'=>$techn_info['mobile']];
         		\think\Queue::later($second, $job, $queues_data, 'ivrCall');
         		\think\Queue::later($delayed_second, $job, $queues_data, 'ivrCall');
		  //  }

		  //  电话次数队列

	        //创建任务： 项目命名空间\模块\文件夹\控制器@方法  10分钟后退款
     		$job = "app\service\QueuesService@orderCall";
     		//延时时间
     		$delayed_second = 600;
     		$queues_data = ['id' => $params['order']['id'],'mobile'=>$techn_info['mobile']];
     		\think\Queue::later($delayed_second, $job, $queues_data, 'orderCall');


    		//延时时间
    // 		$delayed_second = 360+$second;
    // 		$queues_data = ['id' => $params['order']['id'],'mobile'=>$techn_info['mobile']];
    // 		\think\Queue::later($delayed_second, $job, $queues_data, 'orderCall');

    // 		$min_time=db::name('set')->where('id','1')->value('min');

    // 		$delayed_second = 600+$second;
    // 		$queues_data = ['id' => $params['order']['id'],'mobile'=>$techn_info['mobile']];
    // 		\think\Queue::later($delayed_second, $job, $queues_data, 'orderCall');

			//微信模板消息
			//查询技师关联用户公众号的openid
			$openid = Db::name('user_weixin')->where(['user_id' => $techn_info['user_id'], 'identity_type' => 'user', 'client_type' => 'h5'])->value('openid');
			if(!empty($openid))
			{
		        /////////////上方测试，下方正式/////////
		        //查询订单详情
		        $order_detail_title = Db::name('order_detail')->where(['order_id' => $params['order']['id']])->column('title');
		      //  $order_detail_title = implode(',', $order_detail_title);
		        $order_detail_title_new='服务项目:'.implode(',',$order_detail_title);
		      //  foreach ($order_detail_title as $k=>$v){
		      //      $order_detail_title_new.="\n ".($k+1).'.'.$v;
		      //  }
		        //查询下单人
		        $order_address = Db::name('order_address')->where(['order_id' => $params['order']['id']])->find();
		        //查询用户
		        $user_info = Db::name('user')->where(['id' => $params['order']['user_id']])->find();
		        $tem_msg['touser'] = $openid;
		        $tem_msg['template_id'] = 'uhmQUK0MNOSOTHFHmf66Z6OR0piSyTwXNmLYkJl4dBs';
		        $tem_msg['miniprogram'] = [
		        	'appid' => TechnWeixinService::$mini_appid,
		        	'pagepath' => 'pages/order/orderdetail?order_id='.$params['order']['id']
		        ];

		        if($params['order']['budan_id']>0){
		            $first='您好，有客户补单成功';
		            db::name('order')->where('id',$params['order']['budan_id'])->update(['status'=>16]);
		        }else{
		            $first='您好，有客户下单成功';
		        }

		        $tem_msg['data'] = [
		            'first' => [
		                'value' => $first,
		                'color' => '#173177'
		            ],
		            'keyword1' => [
		                'value' => $order_detail_title_new,
		                'color' => '#173177'
		            ],
		            'keyword2' => [
		                'value' => $order_address['name'],
		                'color' => '#173177'
		            ],
		            'keyword3' => [
		                'value' => substr_replace($order_address['mobile'], '****', 3, 4),
		                'color' => '#173177'
		            ],
		            'keyword4' => [
		                'value' => substr_replace($user_info['mobile'], '****', 3, 4),
		                'color' => '#173177'
		            ],
		            'keyword5' => [
		                'value' => $order_address['address'].$order_address['address_des'],
		                'color' => '#173177'
		            ],
		            'remark' => [
		                'value' => '请及时接单',
		                'color' => '#173177'
		            ]
		        ];
				UserWeixinService::send_wx_web_tem_msg($tem_msg);
			}
            $order = Db::name('order')->where('id',$params['order']['id'])->find();
//            发送邮件通知


            $proxy = Db::name('proxy')->where('qu',$order['qu'])->find();
            if (empty($proxy)){
                $proxy = Db::name('proxy')->where('shi',$order['shi'])->find();
            }

            $send = Db::name('email_list')->where('proxy_id','in',[$proxy['proxy_id'],999])->where('status',1)->column('open_id');
            $xm = Db::name('order_detail')->where('order_id',$order['id'])->find();
            $techn = Db::name('techn')->where('id',$order['techn_id'])->find();
            $user_name = Db::name('user')->where('id',$order['user_id'])->find();
//            $msg = '['.$proxy['user_name'].']订单通知: 用户:'.$user_name.',在 '.date('m-d H:i',$order['pay_time']).','.$xm['title'].' *'.$xm['buy_number'].',金额 '.$order['price'].",<br>
//            订单号为".$order['order_no'].",<br>
//            车费为:".$order['travel_price']."<br>
//            待接单技师:".$techn['nickname'].",<br>
//            联系电话:".$techn['mobile'].",<br>
//            已通知技师接单.";

            $msg = '所属城市-【'.$proxy['user_name'].'】<br>
            技师昵称:  '.$techn['nickname'].'<br>       
            联系电话:  '.$techn['mobile'].'<br>
            下单客户:  '.$user_name['nickname'].' <br>  
            联系电话：'.$user_name['mobile'].'<br><br>
           
            
            下单时间：'.date('m-d H:i',$order['pay_time']).'<br>
            服务时间：'.date('m-d H:i',$order['pre_start_time']).'-'.date('H:i',$order['pre_end_time']).'<br><br>
            
            项目名称：'.$xm['title'].'(¥'.$xm['price'].') *'.$xm['buy_number'].'<br>      
            往返路程：¥'.$order['distance'].'km<br>
            往返车费：¥'.$order['travel_price'].'元<br>
            订单总价：¥'.$order['pay_price'].'元<br>';
            $subject = "订单通知";
//            Mail::mailTo($send,$subject,$msg);
            //走队列
            //创建任务： 项目命名空间\模块\文件夹\控制器@方法
            $job = "app\service\QueuesSendEmail@send_email";
            //延时时间
            $delayed_second = 3;
            $queues_data = ['to' => $send,'title'=>$subject,'content'=>$msg];
//            \think\Queue::later($delayed_second, $job, $queues_data, 'send_email');


            //发送公众号消息推送
            foreach ($send as $value){
                if (!empty($value)){
                    SendMuLogic::send_mu($value,$order);
                }
            }
            Db::name('order')->where('id',$order['id'])->update(['send_tong'=>1]);
//            SendMuLogic::send_mu_new('opx6C6vD4elzA71_uMmlvAxovti8',6389,6205);
		}
		return ['code' => 0, 'msg' => '支付成功'];
	}
	
	
	
	
	/**
	 * 订单支付处理--加钟
	 */
	public static function OrderPayHandlejz($params = [])
	{
		//订单信息
		if(empty($params['order']))
		{
			return ['code' => -1, 'msg' => '资源不存在或已被删除'];
		}
		if($params['order']['zftype'] ==1)
		{
			return ['code' => 0, 'msg' => '状态不可操作'];
		}
		
		// 支付参数
		$pay_price = isset($params['pay']['pay_price']) ? $params['pay']['pay_price'] : 0;
		// 开启事务
		Db::startTrans();
		//写入支付日志
		$pay_log_id = Db::name('pay_log')->insertGetId([
			'order_id'      => $params['order']['order_id'],
			'trade_no'      => isset($params['pay']['trade_no']) ? $params['pay']['trade_no'] : '',
			'buyer_user'    => isset($params['pay']['buyer_user']) ? $params['pay']['buyer_user'] : '',
			'pay_price'     => $pay_price,
			'total_price'   => $params['order']['price'],
			'subject'       => isset($params['pay']['subject']) ? $params['pay']['subject'] : '订单支付-加钟',
			'payment'       => $params['payment']['payment'],
			'payment_name'  => $params['payment']['name'],
			'business_type' => 1,
			'add_time' => time()
		]);
		if($pay_log_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '支付日志添加失败'];
		}
		//订单更新数据
		$upd_data = [
			'zftype' => 1,
			'pay_time' => time(),
		];
		//更新订单状态
		if(!Db::name('order_jz')->where(['id' => $params['order']['id']])->update($upd_data))
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单更新失败'];
		}
//        添加加钟的修改时间
        Db::name('order')->where('id',$params['order']['id'])->update(['upd_time'=>time()]);
		//添加状态日志
		$status_array = self::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $params['order']['order_id'],
			'original_status' => 6,
			'new_status' => 5,
			'msg' => '支付[已支付-加钟]',
			'identity_type' => 'user',
			'identity_id' => $params['order']['user_id'],
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单历史状态添加失败'];
		}
		
		
		
		
		//查询技师信息
		$techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
		
		
// 		---------------------------------------------------------
		
		
		
		//写入结算数据
		$balance_data = [];
		//结算剩余百分比
		$balance_surplus_scale = 100;
		//服务剩余费用
		$balance_surplus_price = $params['order']['price'];
		//查询技师等级写入结算数据
		//查询技师实时数据
		$techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();
		
		if(!empty($techn_last_info))
		{
            if ($techn_last_info['jz_bl'] == 0){
                $techn_last_info['jz_bl'] = $techn_last_info['divide_into'];
            }
		    if(!empty($techn_last_info['jz_bl'])){
		        //技师分成比例
				$techn_divide_into = $techn_last_info['jz_bl'];
				//技师分成金额
				$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
				//技师服务费用结算数据
				$techn_service_data = [
					'balance_type' => 1,
					'order_id' => $params['order']['order_id'],
					'identity_type' => 'techn',
					'identity_id' => $params['order']['techn_id'],
					'divide_into' => $techn_divide_into,
					'price' => $params['order']['price'],
					'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
					'msg' => '技师分成',
					'add_time' => time(),
					'upd_time' => time()
				];
				$balance_surplus_scale -= $techn_last_info['jz_bl'];
				$balance_surplus_price -= $techn_service_data['no_money'];
				$balance_data[] = $techn_service_data;
		    }else{
		        //如果技师实时信息存在查询对应等级
    			//检查等级条件
    			$techn_level_map = [
    				'is_delete_time' => 0,
    				'rank' => $techn_last_info['divide_rank'],
    				'proxy_id'=>0
    			];
    			$techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
    			if(!empty($techn_level_info))
    			{
    				//如果技师等级存在
    				//结算服务分成
    				if($balance_surplus_price >= 0.01&&$techn_level_info['divide_into']>0)
    				{
    					//技师分成比例
    					$techn_divide_into = $techn_level_info['divide_into'];
    					//技师分成金额
    					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
    					//技师服务费用结算数据
    					$techn_service_data = [
    						'balance_type' => 1,
    						'order_id' => $params['order']['order_id'],
    						'identity_type' => 'techn',
    						'identity_id' => $params['order']['techn_id'],
    						'divide_into' => $techn_divide_into,
    						'price' => $params['order']['price'],
    						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
    						'msg' => '技师分成',
    						'add_time' => time(),
    						'upd_time' => time()
    					];
    					$balance_surplus_scale -= $techn_level_info['divide_into'];
    					$balance_surplus_price -= $techn_service_data['no_money'];
    					$balance_data[] = $techn_service_data;
    				}
    			}
    		}
	    }
		
		
		//查看机构结算数据
		$proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
		if(!empty($proxy_info))
		{
			if($balance_surplus_price >= 0.01)
			{
				//机构分成比例
				$proxy_commission = 100-$proxy_info['commission']-$techn_divide_into;
				//机构分成金额
				$proxy_no_money = PriceNumberFormat(($proxy_commission/100)*$params['order']['price']);
				//机构结算数据
				$proxy_service_data = [
					'balance_type' => 1,
					'order_id' => $params['order']['order_id'],
					'identity_type' => 'proxy',
					'identity_id' => $proxy_info['proxy_id'],
					'divide_into' => $proxy_commission,
					'price' => $params['order']['price'],
					'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
					'msg' => '机构分成',
					'add_time' => time(),
					'upd_time' => time()
				];
				$balance_surplus_scale -= $proxy_service_data['divide_into'];
				$balance_surplus_price -= $proxy_service_data['no_money'];
				$balance_data[] = $proxy_service_data;
			}
		}
		//系统平台结算数据
		if($balance_surplus_price >= 0.01)
		{
			$balance_data[] = [
				'balance_type' => 1,
				'order_id' => $params['order']['order_id'],
				'identity_type' => 'system',
				'identity_id' => 0,
				'divide_into' => $balance_surplus_scale,
				'price' => $params['order']['price'],
				'no_money' => $balance_surplus_price,
				'msg' => '平台分成',
				'add_time' => time(),
				'upd_time' => time()
			];
		}
		
		if(!empty($balance_data))
		{
			$balance_count = Db::name('balance')->insertAll($balance_data);
			if($balance_count <= 0)
			{
				Db::rollback();
			    return ['code' => -1, 'msg' => '结算数据添加失败'];
			}
		}
		
		$order=db::name('order')->where('id',$params['order']['order_id'])->find();
		
		$local_pre_start_time=$order['pre_start_time'];
		$local_pre_end_time=$order['pre_end_time'];
		if($order['status']==2||$order['status']==3||$order['status']==4||$order['status']==5){
		    $pre_end_time=$order['pre_end_time']+$params['order']['longtime']*60;
		}else{
		    $pre_end_time=time()+$params['order']['longtime']*60;
		}
		
		$orderupdata=[];
		$orderupdata['jztype']=1;
		$orderupdata['local_pre_start_time']=$local_pre_start_time;
		$orderupdata['local_pre_end_time']=$local_pre_end_time;
		$orderupdata['pre_end_time']=$pre_end_time;
		if($order['status']==6){
		    $orderupdata['status']=5;
		}
		
		db::name('order')->where('id',$params['order']['order_id'])->update($orderupdata);
		
		db::name('order')->where('id',$params['order']['order_id'])->setInc('price',$params['order']['price']);
		db::name('order')->where('id',$params['order']['order_id'])->setInc('total_price',$params['order']['price']);
		db::name('order')->where('id',$params['order']['order_id'])->setInc('pay_price',$params['order']['price']);
		
		$order_jzdetail=db::name('order_jzdetail')->where('jz_id',$params['order']['id'])->select();
		
		$order_detail=[];
		
		foreach ($order_jzdetail as $k=>$v){
		    unset($v['id']);
		    $v['type']=1;
		    $order_detail[]=$v;
		}
		
		$a=db::name('order_detail')->insertAll($order_detail);
		
		if($a<=0){
		    Db::rollback();
		    return ['code' => -1, 'msg' => '结算数据添加失败'];
		}
		
		$job = "app\service\QueuesService@order_fw_close";
		//延时时间
		$delayed_second = $pre_end_time-time()-300;
		$queues_data = ['id' => $params['order']['order_id']];
		\think\Queue::later($delayed_second, $job, $queues_data, 'order_fw_close');
		
		
        TechnService::TechnPreTimey($params['order']['techn_id']);
		
		//提交事务
		Db::commit();


//            发送邮件通知

        $order = Db::name('order')->where('id',$params['order']['order_id'])->find();
        $order_jzinfo = Db::name('order_jzdetail')->where('order_id',$params['order']['order_id'])->find();

        $proxy = Db::name('proxy')->where('shi',$order['shi'])->find();
        $send = Db::name('email_list')->where('proxy_id','in',[$proxy['proxy_id'],999])->where('status',1)->column('open_id');
        $xm = Db::name('order_detail')->where('order_id',$order['id'])->find();
        $techn = Db::name('techn')->where('id',$order['techn_id'])->find();
        $user_name = Db::name('user')->where('id',$order['user_id'])->find();
//            $msg = '['.$proxy['user_name'].']订单通知: 用户:'.$user_name.',在 '.date('m-d H:i',$order['pay_time']).','.$xm['title'].' *'.$xm['buy_number'].',金额 '.$order['price'].",<br>
//            订单号为".$order['order_no'].",<br>
//            车费为:".$order['travel_price']."<br>
//            待接单技师:".$techn['nickname'].",<br>
//            联系电话:".$techn['mobile'].",<br>
//            已通知技师接单.";

        $msg = '所属城市-【'.$proxy['user_name'].'】<br>
            技师昵称:  '.$techn['nickname'].'<br>       
            联系电话:  '.$techn['mobile'].'<br>
            下单客户:  '.$user_name['nickname'].' <br>  
            联系电话：'.$user_name['mobile'].'<br><br>
            
            下单时间：'.date('m-d H:i',$order_jzinfo['upd_time']).'<br>
            服务时间：'.date('m-d H:i',$order['pre_start_time']).'-'.date('H:i',$order['pre_end_time']).'<br><br>
            
            项目名称：'.$xm['title'].'(¥'.$xm['price'].') *'.$xm['buy_number'].'<br>      
            加钟项目：'.$order_jzinfo['title'].'(¥'.$order_jzinfo['price'].') *'.$order_jzinfo['buy_number'].'<br>      
            加钟总价：¥'.$order_jzinfo['price']*$order_jzinfo['buy_number'].'元<br>';
        $subject = "订单通知(加钟)";
//        Mail::mailTo($send,$subject,$msg);
        //走队列
        //创建任务： 项目命名空间\模块\文件夹\控制器@方法
        $job = "app\service\QueuesSendEmail@send_email";
        //延时时间
        $delayed_second = 3;
        $queues_data = ['to' => $send,'title'=>$subject,'content'=>$msg];
//        \think\Queue::later($delayed_second, $job, $queues_data, 'send_email');
        foreach ($send as $value){
            if (!empty($value)){
                SendMuLogic::send_mu($value,$order);
            }
        }
		return ['code' => 0, 'msg' => '支付成功'];
	}
	
	
	
	
	
	/**
	 * 订单支付处理--升级
	 */
	public static function OrderPayHandleup($params = [])
	{
		//订单信息
		if(empty($params['order']))
		{
			return ['code' => -1, 'msg' => '资源不存在或已被删除'];
		}
		if($params['order']['zftype'] ==1)
		{
			return ['code' => 0, 'msg' => '状态不可操作'];
		}
		
		// 支付参数
		$pay_price = isset($params['pay']['pay_price']) ? $params['pay']['pay_price'] : 0;
		// 开启事务
		Db::startTrans();
		//写入支付日志
		$pay_log_id = Db::name('pay_log')->insertGetId([
			'order_id'      => $params['order']['order_id'],
			'trade_no'      => isset($params['pay']['trade_no']) ? $params['pay']['trade_no'] : '',
			'buyer_user'    => isset($params['pay']['buyer_user']) ? $params['pay']['buyer_user'] : '',
			'pay_price'     => $pay_price,
			'total_price'   => $params['order']['price'],
			'subject'       => isset($params['pay']['subject']) ? $params['pay']['subject'] : '订单支付-加钟',
			'payment'       => $params['payment']['payment'],
			'payment_name'  => $params['payment']['name'],
			'business_type' => 1,
			'add_time' => time()
		]);
		if($pay_log_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '支付日志添加失败'];
		}
		//订单更新数据
		$upd_data = [
			'zftype' => 1,
			'pay_time' => time()
		];
		//更新订单状态
		if(!Db::name('order_upgrade')->where(['id' => $params['order']['id']])->update($upd_data))
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单更新失败'];
		}
        //添加升级的修改时间
        Db::name('order')->where('id',$params['order']['id'])->update(['upd_time'=>time()]);
		//添加状态日志
		$status_array = self::$status_array;
		$order_status_history_id = Db::name('order_status_history')->insertGetId([
			'order_id' => $params['order']['order_id'],
			'original_status' => 6,
			'new_status' => 5,
			'msg' => '支付[已支付-升级]',
			'identity_type' => 'user',
			'identity_id' => $params['order']['user_id'],
			'add_time' => time()
		]);
		if($order_status_history_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单历史状态添加失败'];
		}
		
		
		
		
		//查询技师信息
		$techn_info = Db::name('techn')->where(['id' => $params['order']['techn_id']])->find();
		
		
// 		---------------------------------------------------------
		
		
		
		//写入结算数据
		$balance_data = [];
		//结算剩余百分比
		$balance_surplus_scale = 100;
		//服务剩余费用
		$balance_surplus_price = $params['order']['price'];
		//查询技师等级写入结算数据
		//查询技师实时数据
		$techn_last_info = Db::name('techn_last')->where(['techn_id' => $params['order']['techn_id']])->find();
		
		if(!empty($techn_last_info))
		{
		    if(!empty($techn_last_info['divide_into'])){
		        //技师分成比例
				$techn_divide_into = $techn_last_info['divide_into'];
				//技师分成金额
				$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
				//技师服务费用结算数据
				$techn_service_data = [
					'balance_type' => 1,
					'order_id' => $params['order']['order_id'],
					'identity_type' => 'techn',
					'identity_id' => $params['order']['techn_id'],
					'divide_into' => $techn_divide_into,
					'price' => $params['order']['price'],
					'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
					'msg' => '技师分成',
					'add_time' => time(),
					'upd_time' => time()
				];
				$balance_surplus_scale -= $techn_service_data['divide_into'];
				$balance_surplus_price -= $techn_service_data['no_money'];
				$balance_data[] = $techn_service_data;
		    }else{
		        //如果技师实时信息存在查询对应等级
    			//检查等级条件
    			$techn_level_map = [
    				'is_delete_time' => 0,
    				'rank' => $techn_last_info['divide_rank'],
    				'proxy_id'=>0
    			];
    			$techn_level_info = Db::name('techn_level')->where($techn_level_map)->find();
    			if(!empty($techn_level_info))
    			{
    				//如果技师等级存在
    				//结算服务分成
    				if($balance_surplus_price >= 0.01)
    				{
    					//技师分成比例
    					$techn_divide_into = $techn_level_info['divide_into'];
    					//技师分成金额
    					$techn_no_money = PriceNumberFormat(($techn_divide_into/100)*$params['order']['price']);
    					//技师服务费用结算数据
    					$techn_service_data = [
    						'balance_type' => 1,
    						'order_id' => $params['order']['order_id'],
    						'identity_type' => 'techn',
    						'identity_id' => $params['order']['techn_id'],
    						'divide_into' => $techn_divide_into,
    						'price' => $params['order']['price'],
    						'no_money' => $techn_no_money >= 0.01 ? $techn_no_money : $params['order']['price'],
    						'msg' => '技师分成',
    						'add_time' => time(),
    						'upd_time' => time()
    					];
    					$balance_surplus_scale -= $techn_service_data['divide_into'];
    					$balance_surplus_price -= $techn_service_data['no_money'];
    					$balance_data[] = $techn_service_data;
    				}
    			}
    		}
	    }
		
		
		//查看机构结算数据
		$proxy_info = Db::name('proxy')->where(['shi' => $techn_info['city'], 'commission' => ['GT', 0]])->find();
		if(!empty($proxy_info))
		{
			if($balance_surplus_price >= 0.01)
			{
				//机构分成比例
				$proxy_commission = 100-$proxy_info['commission']-$techn_divide_into;
				//机构分成金额
				$proxy_no_money = PriceNumberFormat(($proxy_commission/100)*$params['order']['price']);
				//机构结算数据
				$proxy_service_data = [
					'balance_type' => 1,
					'order_id' => $params['order']['order_id'],
					'identity_type' => 'proxy',
					'identity_id' => $proxy_info['proxy_id'],
					'divide_into' => $proxy_commission,
					'price' => $params['order']['price'],
					'no_money' => $proxy_no_money >= 0.01 ? $proxy_no_money : $balance_surplus_price,
					'msg' => '机构分成',
					'add_time' => time(),
					'upd_time' => time()
				];
				$balance_surplus_scale -= $proxy_service_data['divide_into'];
				$balance_surplus_price -= $proxy_service_data['no_money'];
				$balance_data[] = $proxy_service_data;
			}
		}
		//系统平台结算数据
		if($balance_surplus_price >= 0.01)
		{
			$balance_data[] = [
				'balance_type' => 1,
				'order_id' => $params['order']['order_id'],
				'identity_type' => 'system',
				'identity_id' => 0,
				'divide_into' => $balance_surplus_scale,
				'price' => $params['order']['price'],
				'no_money' => $balance_surplus_price,
				'msg' => '平台分成',
				'add_time' => time(),
				'upd_time' => time()
			];
		}
		
		if(!empty($balance_data))
		{
			$balance_count = Db::name('balance')->insertAll($balance_data);
			if($balance_count <= 0)
			{
				Db::rollback();
			    return ['code' => -1, 'msg' => '结算数据添加失败'];
			}
		}
		
		$order=db::name('order')->where('id',$params['order']['order_id'])->find();
		
		$local_pre_start_time=$order['pre_start_time'];
		$local_pre_end_time=$order['pre_end_time'];
		
	    $pre_end_time=$order['pre_start_time']+$params['order']['longtime']*60;
		    
		db::name('order')->where('id',$params['order']['order_id'])->update(['jztype'=>1,'local_pre_start_time'=>$local_pre_start_time,'local_pre_end_time'=>$local_pre_end_time,'pre_end_time'=>$pre_end_time,'status'=>5]);
		
		db::name('order')->where('id',$params['order']['order_id'])->setInc('price',$params['order']['price']);
		db::name('order')->where('id',$params['order']['order_id'])->setInc('total_price',$params['order']['price']);
		db::name('order')->where('id',$params['order']['order_id'])->setInc('pay_price',$params['order']['price']);
		
		$order_jzdetail=db::name('order_updetail')->where('up_id',$params['order']['id'])->select();
		
		$order_detail=[];
		
		foreach ($order_jzdetail as $k=>$v){
		    unset($v['id']);
		    $v['uptype']=1;
		    $order_detail[]=$v;
		}
		db::name('order_detail')->where('order_id',$params['order']['order_id'])->update(['showtype'=>2]);
		
		$a=db::name('order_detail')->insertAll($order_detail);
		
		if($a<=0){
		    Db::rollback();
		    return ['code' => -1, 'msg' => '结算数据添加失败'];
		}
		
		$job = "app\service\QueuesService@order_fw_close";
		//延时时间
		$delayed_second = $pre_end_time-time()-300;
		$queues_data = ['id' => $params['order']['order_id']];
		\think\Queue::later($delayed_second, $job, $queues_data, 'order_fw_close');
		
		//提交事务
		Db::commit();
		
		
        TechnService::TechnPreTimey($params['order']['techn_id']);


//            发送邮件通知
        $order = Db::name('order')->where('id',$params['order']['order_id'])->find();
        $order_sjinfo = Db::name('order_upgrade')->where('order_id',$params['order']['order_id'])->find();

        $proxy = Db::name('proxy')->where('shi',$order['shi'])->find();
        $send = Db::name('email_list')->where('proxy_id','in',[$proxy['proxy_id'],999])->where('status',1)->column('open_id');
        $xm = Db::name('order_detail')->where('order_id',$order['id'])->where('up_id',0)->find();
        $sj_xm = Db::name('order_detail')->where('order_id',$order['id'])->where('up_id','>',0)->find();
        $techn = Db::name('techn')->where('id',$order['techn_id'])->find();
        $user_name = Db::name('user')->where('id',$order['user_id'])->find();
//            $msg = '['.$proxy['user_name'].']订单通知: 用户:'.$user_name.',在 '.date('m-d H:i',$order['pay_time']).','.$xm['title'].' *'.$xm['buy_number'].',金额 '.$order['price'].",<br>
//            订单号为".$order['order_no'].",<br>
//            车费为:".$order['travel_price']."<br>
//            待接单技师:".$techn['nickname'].",<br>
//            联系电话:".$techn['mobile'].",<br>
//            已通知技师接单.";

//        $msg = '所属城市-【'.$proxy['user_name'].'】<br>
//            技师昵称:  '.$techn['nickname'].'<br>
//            联系电话:  '.$techn['mobile'].'<br>
//            下单客户:  '.$user_name['nickname'].' <br>
//            联系电话：'.$user_name['mobile'].'<br><br>
//
//            下单时间：'.date('m-d H:i',$order_sjinfo['pay_time']).'<br>
//            服务时间：'.date('m-d H:i',$order['pre_start_time']).'-'.date('H:i',$order['pre_end_time']).'<br><br>
//
//            项目名称：'.$xm['title'].'(¥'.$xm['price'].') *'.$xm['buy_number'].'<br>
//            升级项目：'.$sj_xm['title'].'(¥'.$sj_xm['price'].') *'.$sj_xm['buy_number'].'<br>
//            升级补价：¥'.$order_sjinfo['price'].'元<br>';
//        $subject = "订单通知(升级)";
//        Mail::mailTo($send,$subject,$msg);
        //走队列
        //创建任务： 项目命名空间\模块\文件夹\控制器@方法
//        $job = "app\service\QueuesSendEmail@send_email";
        //延时时间
//        $delayed_second = 3;
//        $queues_data = ['to' => $send,'title'=>$subject,'content'=>$msg];
//        \think\Queue::later($delayed_second, $job, $queues_data, 'send_email');
        foreach ($send as $value){
            if (!empty($value)){
                SendMuLogic::send_mu($value,$order);
            }
        }
		return ['code' => 0, 'msg' => '支付成功'];
	}
	
	
	
	
	public static function OrderPayHandle_rechange($params = [])
	{
		//订单信息
		if(empty($params['order']))
		{
			return ['code' => -1, 'msg' => '资源不存在或已被删除'];
		}
		if($params['order']['status'] ==1)
		{
			return ['code' => 0, 'msg' => '状态不可操作'];
		}
		
		// 支付参数
		$pay_price = isset($params['pay']['pay_price']) ? $params['pay']['pay_price'] : 0;
		// 开启事务
		Db::startTrans();
		//写入支付日志
		$pay_log_id = Db::name('pay_log')->insertGetId([
			'order_id'      => $params['order']['id'],
			'trade_no'      => isset($params['pay']['trade_no']) ? $params['pay']['trade_no'] : '',
			'buyer_user'    => isset($params['pay']['buyer_user']) ? $params['pay']['buyer_user'] : '',
			'pay_price'     => $pay_price,
			'total_price'   => $params['order']['price'],
			'subject'       => isset($params['pay']['subject']) ? $params['pay']['subject'] : '订单支付-充值',
			'payment'       => 'Weixin',
			'payment_name'  => '微信',
			'business_type' => 1,
			'add_time' => time()
		]);
		if($pay_log_id <= 0)
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '支付日志添加失败'];
		}
		//订单更新数据
		$upd_data = [
			'status' => 1,
			'pay_time' => time()
		];
		//更新订单状态
		if(!Db::name('user_rechange')->where(['id' => $params['order']['id']])->update($upd_data))
		{
			Db::rollback();
			return ['code' => -1, 'msg' => '订单更新失败'];
		}
		
		$original_money=db::name('user')->where('id',$params['order']['user_id'])->value('money');
		
		
		$price=$params['order']['price']+$params['order']['zprice'];
		
		if(!db::name('user')->where('id',$params['order']['user_id'])->setInc('money',$price)){
		    Db::rollback();
		    return ['code' => -1, 'msg' => '结算数据添加失败'];
		}
		if($params['order']['uptel']>0){
	        $techn=db::name('techn')->where('mobile',$params['order']['uptel'])->find();
	        if(!empty($techn)){
	            db::name('techn')->where('mobile',$params['order']['uptel'])->setInc('jifen',$params['order']['fprice']);
	            db::name('techn_last')->where('techn_id',$techn['id'])->setInc('total_integral',$params['order']['fprice']);
	        }
	    }
		//余额日志
        $money_log_id = Db::name('money_log')->insertGetId([
            'identity_type' => 'user',
            'identity_id' => $params['order']['user_id'],
            'business_type' => 3,
            'money_type' => 0,
            'operation_type' => 1,
            'operation_money' => $price,
            'original_money' => $original_money,
            'latest_money' => $original_money+$price,
            'msg' => '余额充值',
            'add_time' => time()
        ]);
        if($money_log_id <= 0)
        {
            Db::rollback();
            return ['code' => -101, 'msg' => '余额日志添加失败'];
        }
        //积分添加
        log::write('order_info',$params['order']['id']);
        $pd = Db::name('user_rechange')->where('id',$params['order']['id'])->find();
        if (!empty($pd) && $pd['status'] == 1){
            if (!empty($params['order']['uptel'])){
                $techn_info = Db::name('techn')->where('mobile',$params['order']['uptel'])->find();
                if (!empty($techn_info)){
                    $jf = Db::name('techn_last')->where('techn_id',$techn_info['id'])->find();
                    $he = $jf['temp_integral'];
                    if ($he > 0){
                        $update_jf = ['total_integral'=>$he,'temp_integral'=>0];
                        Db::name('techn_last')->where('techn_id',$techn_info['id'])->update($update_jf);
                    }
                }
            }
        }
		//提交事务
		Db::commit();
		
		return ['code' => 0, 'msg' => '支付成功'];
	    
	}
	
}